<template>
  <view class="contact-page">
   <view class="article-content" v-show="form.content">
   	 <u-parse :content="form.content" ></u-parse>
   </view>
    <!-- 表单区域 -->
    <view class="form-container">
      <u-form :model="form" :rules="rules" ref="uForm" labelWidth="140">
        <!-- 需求信息 -->
        <view class="form-section">
          <view class="section-title">您的需求</view>
          <u-form-item label="需求" prop="product" borderBottom>
            <u-input
              v-model="form.product"
              placeholder="请选择需求"
              border="none"
              disabled
              disabledColor="#ffffff"
            ></u-input>
          </u-form-item>
          <u-form-item label="补充说明" prop="description" borderBottom>
            <u-textarea
              v-model="form.description"
              placeholder="请简要描述您的具体需求"
              height="100"
              border="none"
            ></u-textarea>
          </u-form-item>
        </view>
         <!-- 基本信息 -->
        <view class="form-section">
          <view class="section-title">基本信息</view>
          <u-form-item label="姓名" prop="name" borderBottom>
            <u-input
              v-model="form.name"
              placeholder="请输入您的姓名"
              border="none"
            ></u-input>
          </u-form-item>
          
          <u-form-item label="手机号码" prop="phone" borderBottom>
            <u-input
              v-model="form.phone"
              placeholder="请输入您的手机号码"
              border="none"
              type="number"
            ></u-input>
          </u-form-item>
          
          <u-form-item label="所在城市" prop="city" borderBottom @click="showCityPicker = true">
            <u-input
              v-model="form.city"
              placeholder="请选择所在城市"
              border="none"
              disabled
              disabledColor="#ffffff"
            ></u-input>
            <u-icon slot="right" name="arrow-right"></u-icon>
          </u-form-item>
        </view>
        <!-- 提交按钮 -->
        <view class="submit-btn-container">
          <u-button
            type="primary"
            :customStyle="{
              backgroundColor: primaryColor,
              color: '#fff',
              height: '90rpx',
              borderRadius: '45rpx'
            }"
            @click="submitForm"
            :loading="loading"
          >
            {{ loading ? '提交中...' : '提交需求' }}
          </u-button>
        </view>
      </u-form>

      <view class="service-note">
        <text>提交后我们的业务经理将在24小时内与您联系，请保持手机畅通</text>
      </view>
    </view>

    <!-- 城市选择器 -->
    <u-picker
      :show="showCityPicker"
      :columns="cityColumns"
      keyName="label"
      @confirm="confirmCity"
      @cancel="showCityPicker = false"
    ></u-picker>

    <!-- 需求类型选择器 -->
    <u-picker
      :show="showDemandPicker"
      :columns="demandColumns"
      keyName="label"
      @confirm="confirmDemand"
      @cancel="showDemandPicker = false"
    ></u-picker>

  </view>
</template>

<script>
const getUrlParams=  function(url) {
	// 通过 ? 分割获取后面的参数字符串
	let obj = {};
	if(!!url){
		let urlStr = url.split('?')[1]
		// 创建空对象存储参数
		// 再通过 & 将每一个参数单独分割出来
		let paramsArr = urlStr.split('&')
		for(let i = 0,len = paramsArr.length;i < len;i++){
			// 再通过 = 将每一个参数分割为 key:value 的形式
			let arr = paramsArr[i].split('=')
			obj[arr[0]] = arr[1];
		}
	}
	
	return obj
}
	const Odb=uniCloud.importObject('mydb-page')
export default {
  data() {
    return {
      primaryColor: '#007AFF',
      pageTitle: '客户需求收集',
      loading: false,
      showCityPicker: false,
      showDemandPicker: false,
      showTermPicker: false,
      form: {
        name: '',
        phone: '',
        city: '',
        product: '',
        loanAmount: '',
        loanTerm: '',
        description: '',
		inviteCode:'',
		content:''
      },
      rules: {
        name: [
          { required: true, message: '请输入姓名', trigger: 'blur' },
          { min: 2, max: 10, message: '姓名长度在2-10个字符', trigger: 'blur' }
        ],
        phone: [
          { required: true, message: '请输入手机号码', trigger: 'blur' },
          { 
            validator: (rule, value, callback) => {
              return uni.$u.test.mobile(value);
            }, 
            message: '手机号码格式不正确', 
            trigger: 'blur' 
          }
        ],
        city: [
          { required: true, message: '请选择所在城市', trigger: 'change' }
        ],
        product: [
          { required: true, message: '请选择需求类型', trigger: 'change' }
        ],
        loanAmount: [
          { required: true, message: '请输入贷款金额', trigger: 'blur' }
        ],
        loanTerm: [
          { required: true, message: '请选择贷款期限', trigger: 'change' }
        ]
      },
      cityColumns: [
        [
          { label: '北京', value: '北京' },
          { label: '上海', value: '上海' },
          { label: '广州', value: '广州' },
          { label: '深圳', value: '深圳' },
          { label: '惠州', value: '惠州' },
          { label: '东莞', value: '东莞' },
          { label: '河源', value: '河源' },
          { label: '汕尾', value: '汕尾' }
        ]
      ],
      demandColumns: []
    }
  },
  onLoad(options) {
    if (Object.keys(options).length) {
		const params = options.q ? decodeURIComponent(options.q) : options
		let querys = typeof params =='string' ?  getUrlParams(params) : {}
		let { inviteCode } = querys
		inviteCode && (this.form.inviteCode=inviteCode)
	}
    if (options.type) {
      this.form.product = options.type;
    }
    if (options.productId) {
	  Odb.getProductDetail({productId:options.productId}).then((res)=>{
	  	this.form.content=res.data.content
		this.form.product = res.data.title;
	  })
    }
    this.getProductCategories()
  },
  onReady() {
    this.$refs.uForm.setRules(this.rules);
  },
  methods: {
    getProductCategories(){
      let Odb=uniCloud.importObject('mydb-page')
      Odb.getProductCategories().then((res)=>{
        if(res.status){
          this.demandColumns=res.data.map(item=>({
            label:item.navtitle,
            value:item.navtitle
          }))
        }
      })
    },
    // 确认城市选择
    confirmCity(e) {
      this.form.city = e.value[0].value;
      this.showCityPicker = false;
    },
    
    // 确认需求类型选择
    confirmDemand(e) {
      this.form.product = e.value[0].value;
      this.showDemandPicker = false;
    },
    
    
    // 提交表单
    submitForm() {
      this.$refs.uForm.validate(valid => {
        if (valid) {
          this.loading = true;
			let Odb=uniCloud.importObject('mydb-customer')
			Odb.saveCustomer(this.form).then((res)=>{
				this.loading = false;
				if(res.status){
					// 显示成功提示
					uni.showToast({
					  title: '提交成功,等待业务员联系',
					  icon: 'none',
					  duration: 2000
					});
					// 跳转回首页或显示成功页面
					setTimeout(() => {
					  uni.navigateBack();
					}, 2000);
				}else{
					uni.showToast({
					  title: result.errMsg,
					  icon: 'error'
					});
				}
			})
        } else {
          console.log('验证失败');
        }
      });
    }
  }
}
</script>

<style lang="scss" scoped>
.contact-page {
  min-height: 100vh;
  background-color: #f5f5f5;
}

.form-container {
  padding: 30rpx;
}

.form-section {
  background-color: #fff;
  border-radius: 16rpx;
  padding: 0 30rpx;
  margin-bottom: 30rpx;
  
  .section-title {
    font-size: 32rpx;
    font-weight: bold;
    padding: 30rpx 0 20rpx;
    color: #333;
    border-bottom: 1rpx solid #eee;
  }
}

.submit-btn-container {
  padding: 40rpx 0 20rpx;
}

.service-note {
  text-align: center;
  padding: 20rpx 0;
  color: #999;
  font-size: 24rpx;
}

// 表单样式调整
::v-deep .u-form-item {
  padding: 24rpx 0;
  
  .u-form-item__body {
    align-items: center;
  }
}

::v-deep .u-input {
  padding: 0 !important;
}

::v-deep .u-textarea {
  padding: 20rpx 0 !important;
}
</style>